﻿using Mysoft.ModelAnalysis.Models;
using Mysoft.Utility;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Web.UI.WebControls;
using System.Web.WebSockets;
using System.Xml;
using System.Xml.Serialization;
using 检查页面开放.Business;
using 检查页面开放.Models;
using 检查页面开放.Utility;

namespace 检查页面开放.Controllers
{
    /// <summary>
    /// 分库相关检查
    /// </summary>
    public class FkController : Controller
    {
        // GET: Fk
        public ActionResult Index()
        {
            //获取所有实体
            List<MetadataEntity> entities = MetaDataOp.GetMetadataEntities();
            return View(entities);
        }

        /// <summary>
        /// 添加GUID
        /// </summary>
        public void AddBuguid()
        {
            List<MetadataEntity> entities = MetaDataOp.GetMetadataEntities();
            var errorEntity = entities.Where(t => t.IsEnableIsolateForCompany == true
            && (t.Attributes.MetadataAttributes.Any(m => string.Equals(m.Name, "buguid", StringComparison.OrdinalIgnoreCase)) == false)
            );

            foreach (var entity in errorEntity)
            {
                var fullName = entity.FullName;
                bool isXmlns = false;//xmlns:p4

                StringBuilder allTxt = new StringBuilder();
                foreach (string str in System.IO.File.ReadAllLines(fullName, Encoding.Default))
                {
                    if (isXmlns == false && str.IndexOf("xmlns:p4") > 0)
                    {
                        isXmlns = true;
                    }
                    if (string.Equals(str.Trim(), "</Attributes>", StringComparison.OrdinalIgnoreCase))
                    {
                        if (isXmlns == false)
                        {
                            allTxt.AppendLine("		<MetadataAttribute metadataStatus=\"Product\">\r\n" +
                "    		<AttributeId>" + Guid.NewGuid().ToString() + "</AttributeId>\r\n" +
                "    		<Name>BUGUID</Name>\r\n" +
                "    		<DisplayName>公司标识</DisplayName>\r\n" +
                "    		<AttributeType>Guid</AttributeType>\r\n" +
                "    		<DbType>uniqueidentifier</DbType>\r\n" +
                "    		<RequiredLevel>none</RequiredLevel>\r\n" +
                "    		<Remark />\r\n" +
                "    		<Length xsi:nil=\"true\" />\r\n" +
                "    		<IsNullable>true</IsNullable>\r\n" +
                "    		<ColumnNumber>7</ColumnNumber>\r\n" +
                "    		<IsPrimaryAttribute>false</IsPrimaryAttribute>\r\n" +
                "    		<DecimalPrecision xsi:nil=\"true\" />\r\n" +
                "    		<RelationshipId xsi:nil=\"true\" />\r\n" +
                "    		<AllowQuickFind>true</AllowQuickFind>\r\n" +
                "    		<OptionsEnum />\r\n" +
                "    		<MultiSelect>false</MultiSelect>\r\n" +
                "    		<LookupPrimaryEntityId xsi:nil=\"true\" />\r\n" +
                "    		<IsThousandth>false</IsThousandth>\r\n" +
                "    		<IsRedundance>false</IsRedundance>\r\n" +
                "    		<IsIdentity>false</IsIdentity>\r\n" +
                "    		<IsEnum>false</IsEnum>\r\n" +
                "    		<EnumInfos />\r\n" +
                "		</MetadataAttribute>");
                        }
                        else
                        {

                            allTxt.AppendLine("    <MetadataAttribute metadataStatus=\"Product\">\r\n" +
"      <AttributeId>" + Guid.NewGuid().ToString() + "</AttributeId>\r\n" +
"      <Name>BUGUID</Name>\r\n" +
"      <DisplayName>公司标识</DisplayName>\r\n" +
"      <AttributeType>Guid</AttributeType>\r\n" +
"      <DbType>uniqueidentifier</DbType>\r\n" +
"      <RequiredLevel>none</RequiredLevel>\r\n" +
"      <Remark />\r\n" +
"      <Length>0</Length>\r\n" +
"      <IsNullable>true</IsNullable>\r\n" +
"      <ColumnNumber>10</ColumnNumber>\r\n" +
"      <IsPrimaryAttribute>false</IsPrimaryAttribute>\r\n" +
"      <DecimalPrecision>0</DecimalPrecision>\r\n" +
"      <RelationshipId p4:nil=\"true\" xmlns:p4=\"http://www.w3.org/2001/XMLSchema-instance\" />\r\n" +
"      <AllowQuickFind>true</AllowQuickFind>\r\n" +
"      <OptionsEnum />\r\n" +
"      <MultiSelect>false</MultiSelect>\r\n" +
"      <LookupPrimaryEntityId p4:nil=\"true\" xmlns:p4=\"http://www.w3.org/2001/XMLSchema-instance\" />\r\n" +
"      <IsThousandth>false</IsThousandth>\r\n" +
"    </MetadataAttribute>");
                        }
                    }
                    allTxt.AppendLine(str);
                }
                FileHelper.WriteFile(fullName, allTxt.ToString());
            }
        }


        List<string> expectTable = new List<string> { "s_CwfxDcTemp", "s_FeeDcTemp", "s_Barcode", "p_CstAttribute", "s_GetInDcTemp", "YGZ_QueueChangeRecord", "s_AppProcess", "s_AppProcessDetail" };

        /// <summary>
        /// 获取分库
        /// </summary>
        /// <param name="fkSqlConn"></param>
        /// <param name="zkBuGuid">主库公司id</param>
        /// <returns></returns>
        public string CaleCount(string fkSqlConn, string zkSqlConn, Guid fkBuGuid)
        {
            //
            string fkXml = System.IO.File.ReadAllText(PathConst.Fk, Encoding.Default);
            var fkTableModel = XmlUtility.DeserializeToObject<FkTableModel>(fkXml);
            List<MetadataEntity> entities = MetaDataOp.GetMetadataEntities();
            entities.RemoveAll(t => expectTable.Contains(t.Name));

            //不分库的表在分库上查询
            List<FkResultDto> zkNfkbResultDtos = GetZkData(fkSqlConn, Guid.Empty, fkTableModel, entities.FindAll(t => t.IsEnableIsolateForCompany == false));
            //所有表在主库上查询
            List<FkResultDto> fkResultDtos = GetZkData(zkSqlConn, fkBuGuid, fkTableModel, entities);

            //分库的表在分库上查询
            List<FkResultDto> fkFk = GetZkData(fkSqlConn, fkBuGuid, fkTableModel, entities.FindAll(t => t.IsEnableIsolateForCompany == true));
            //--1、只要分库表没有数据（在分库上查询），过滤掉数据 > 0的数据 
            List<FkResultDto> fkErrorData = fkFk.FindAll(t => t.IsCal == true && t.IsFk == true && t.Count == 0);

            //--2、只要分库的表（在主库上查询），显示数据 > 0的数据
            List<FkResultDto> zkErrorData = fkResultDtos.FindAll(t => t.IsCal == true && t.IsFk == true && t.Count > 0);

            List<FkResultDto> bfkErrorData = new List<FkResultDto>();
            //--3、不分库的表，在两个库上都有数据，数据要相等
            foreach (var zk in zkNfkbResultDtos.FindAll(t => t.IsCal == true && t.IsFk == false))
            {
                var fk = fkResultDtos.First(t => t.TableName == zk.TableName);
                if (zk.Count != fk.Count)
                {
                    bfkErrorData.Add(fk);
                }
            }
            return Newtonsoft.Json.JsonConvert.SerializeObject(new FkUIResult { FkbNoData = fkErrorData, FkbZkNoData = zkErrorData, BfkbNoEqual = bfkErrorData, NoCal = fkResultDtos.FindAll(t => t.IsCal == false) });
        }

        /// <summary>
        /// 在主库中获取不分库的数据
        /// </summary>
        /// <param name="sqlConn"></param>
        /// <param name="fkTableModel"></param>
        /// <param name="entities"></param>
        /// <returns></returns>
        private static List<FkResultDto> GetZkData(string sqlConn, Guid buguid, FkTableModel fkTableModel, List<MetadataEntity> entities)
        {
            List<FkResultDto> fkResultDtos = new List<FkResultDto>();
            DataAccess dataAccess = new DataAccess(sqlConn);
            SqlParameter[] sqlParameters = new SqlParameter[] { new SqlParameter("buguid", buguid) };
            foreach (var item in entities)
            {
                FkResultDto fkResultDto = new FkResultDto();
                fkResultDto.TableName = item.Name;
                fkResultDto.IsFk = item.IsEnableIsolateForCompany;
                fkResultDto.IsCal = true;
                var fkSql = fkTableModel.CommandList.FirstOrDefault(t => t.Name.ToLower() == item.Name.ToLower());
                if (fkSql == null)
                {
                    fkResultDto.IsCal = false;
                }
                else
                {
                    fkResultDto.Count = (int)dataAccess.ExecuteScalar(fkSql.Sql, System.Data.CommandType.Text, sqlParameters);
                }
                fkResultDtos.Add(fkResultDto);
            }

            return fkResultDtos;
        }


        // 检查某个字段是否有空值
        public ActionResult CheckFieldNull()
        {
            return View();
        }

        // 检查某个字段
        public string CheckFieldAction(string sqlconn, string filed)
        {
            List<string> result = new List<string>();
            var sql = FileHelper.GetTxt(PathConst.CheckFieldAction);
            DataAccess dataAccess = new DataAccess(sqlconn);
            DataTable datatable = dataAccess.ExecuteDataset(sql, System.Data.CommandType.Text, null).Tables[0];
            foreach (DataRow row in datatable.Rows)
            {
                var tableName = row["name"].ToString();
                string searchSql = $"SELECT COUNT(1) FROM {tableName} WHERE {filed} IS NULL";
                int count = (int)dataAccess.ExecuteScalar(searchSql, System.Data.CommandType.Text, null);
                if (count > 0)
                {
                    result.Add(tableName);
                }
            }
            return result.ToJson();
        }
    }

}